from ui import ImageProcessorUI
from .base import ImageProcessor
import numpy as np
import cv2
from PIL import Image

class MorphologyProcessor(ImageProcessor):
    def process(self, image: Image.Image, **kwargs) -> Image.Image:
        """
        对图像进行形态学操作（腐蚀或膨胀）。
        参数:
        - image: 输入图像 (PIL Image)
        - operation: 操作类型 ("erosion" 腐蚀 或 "dilation" 膨胀)
        - kernel_size: 核大小 (奇数，例如 3, 5, 7)
        返回:
        - Image.Image: 处理后的图像
        """
        operation = kwargs.get("operation", "erosion")
        kernel_size = int(kwargs.get("kernel_size", 3))
        if kernel_size % 2 == 0:
            raise ValueError("核大小必须为奇数")
        # 将图像转换为 NumPy 数组
        img_array = np.array(image)
        # 定义结构元素（核）
        kernel = np.ones((kernel_size, kernel_size), np.uint8)
        # 执行形态学操作
        if operation == "erosion":
            processed = cv2.erode(img_array, kernel, iterations=1)
        elif operation == "dilation":
            processed = cv2.dilate(img_array, kernel, iterations=1)
        elif operation == "opening":  # 开运算
            processed = cv2.morphologyEx(img_array, cv2.MORPH_OPEN, kernel)
        elif operation == "closing":  # 闭运算
            processed = cv2.morphologyEx(img_array, cv2.MORPH_CLOSE, kernel)
        else:
            raise ValueError(f"未知的形态学操作: {operation}")
        return Image.fromarray(processed)

    def get_ui_parameters(self, ui: "ImageProcessorUI") -> dict:
        """
        从 UI 获取参数
        """
        try:
            operation = ui.morphology_operation_var.get()
            kernel_size = float(ui.morphology_kernel_scale.get())
            return {
                "operation": operation,
                "kernel_size": kernel_size
            }
        except Exception as e:
            ui.show_error(f"获取参数失败: {e}")
            return {}